import React, { useEffect, useState } from "react";
import {
    Button,
    Chip,
    Spinner,
    Tooltip,
    Divider
} from "@nextui-org/react";
import { ShareItem, cancelShare, getUserShares } from "@/app/service/shareService.tsx";
import { IoCopyOutline } from "react-icons/io5";
import { MdOutlineOpenInNew } from "react-icons/md";
import { HiOutlineTrash } from "react-icons/hi";
import { FiLink } from "react-icons/fi";
import { BiArrowBack } from "react-icons/bi";
import { CgNotes } from "react-icons/cg";
import dayjs from "dayjs";
import copy from "copy-to-clipboard";
import ToastUtil from "@/app/utils/toastUtil";
import { useRouter } from 'next/navigation';

export default function ShareManage() {
    const router = useRouter();
    // 状态定义
    const [isLoading, setIsLoading] = useState(true);
    const [shares, setShares] = useState<any[]>([]);
    const [total, setTotal] = useState(0);
    const [page, setPage] = useState(1);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    const [selectedShareId, setSelectedShareId] = useState<number | null>(null);

    // 分页设置
    const pageSize = 12;

    // 初次加载和分页变化时获取数据
    useEffect(() => {
        fetchShares();
    }, [page]);

    // 获取分享列表
    const fetchShares = async () => {
        setIsLoading(true);
        try {
            console.log("开始获取分享列表 - 页码:", page);
            // 获取分享数据
            const response = await getUserShares(page, pageSize);
            console.log("分享列表API响应:", response);
            
            if (response) {
                // 检查不同的响应格式
                if (response.code === 200 && response.data) {
                    // 标准格式: { code: 200, data: { records: [], total: 0 } }
                    console.log("标准响应格式, 记录数:", response.data.records?.length);
                    setShares(response.data.records || []);
                    setTotal(response.data.total || 0);
                } else if (response.records) {
                    // 简化格式: { records: [], total: 0 }
                    console.log("简化响应格式, 记录数:", response.records.length);
                    setShares(response.records);
                    setTotal(response.total || 0);
                } else {
                    console.log("未知响应格式:", JSON.stringify(response));
                    setShares([]);
                    setTotal(0);
                }
            } else {
                console.log("响应为空");
                setShares([]);
                setTotal(0);
            }
        } catch (error) {
            console.error("获取分享列表失败:", error);
            setShares([]);
            setTotal(0);
        } finally {
            setIsLoading(false);
        }
    };

    // 处理取消分享
    const handleCancelShare = async (shareId: number) => {
        try {
            await cancelShare(shareId);
            fetchShares();
            setShowDeleteConfirm(false);
            setSelectedShareId(null);
        } catch (error) {
            console.error("Failed to cancel share:", error);
        }
    };

    // 复制分享链接
    const copyShareLink = (token: string) => {
        const link = `${window.location.origin}/view/${token}`;
        copy(link);
        ToastUtil("分享链接已复制到剪贴板", "🎉", "success");
    };

    // 打开分享链接
    const openShareLink = (token: string) => {
        const link = `${window.location.origin}/view/${token}`;
        window.open(link, "_blank");
    };

    // 查看对应笔记
    const openNote = (noteId: number) => {
        router.push(`/note/${noteId}`);
    };

    // 格式化日期显示
    const formatDate = (dateString: string) => {
        if (!dateString) return "未设置日期";
        return dayjs(dateString).format("YYYY-MM-DD HH:mm");
    };

    // 计算是否已过期
    const isExpired = (dateString: string) => {
        if (!dateString) return false;
        return dayjs(dateString).isBefore(dayjs());
    };

    // 返回上一页
    const handleGoBack = () => {
        router.back();
    };

    return (
        <div className="w-full px-4 py-6 bg-background">
            {/* 简洁的页面标题 */}
            <div className="mb-6">
                <div className="flex items-center gap-2 mb-1">
                    <Button
                        isIconOnly
                        size="sm"
                        variant="light"
                        aria-label="返回"
                        onPress={handleGoBack}
                    >
                        <BiArrowBack size={18} />
                    </Button>
                    <FiLink className="text-primary" size={20} />
                    <h1 className="text-xl font-semibold">我的分享</h1>
                </div>
                <Divider className="mt-2" />
            </div>

            {/* 内容区域 */}
            {isLoading ? (
                <div className="flex justify-center items-center h-64">
                    <Spinner color="primary" label="加载中..." />
                </div>
            ) : shares.length === 0 ? (
                <div className="flex flex-col justify-center items-center h-64 gap-4">
                    <p className="text-default-500">暂无分享记录</p>
                </div>
            ) : (
                <>
                    {/* 自定义网格布局 */}
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {shares.map((share) => (
                            <div 
                                key={share.id} 
                                className="border border-default-200 rounded-lg p-4 bg-white dark:bg-default-50 hover:border-primary transition-colors cursor-pointer"
                            >
                                <div className="flex justify-between items-start mb-3">
                                    <div className="flex items-center gap-2" onClick={() => openNote(share.noteId)}>
                                        <CgNotes size={22} className="text-primary" />
                                        <h3 className="font-medium text-foreground line-clamp-1">
                                            {share.noteTitle || `笔记 #${share.noteId}`}
                                        </h3>
                                    </div>
                                    <Chip
                                        size="sm"
                                        variant="flat"
                                        color={share.permission === "WRITE" ? "warning" : "success"}
                                    >
                                        {share.permission === "WRITE" ? "可编辑" : "只读"}
                                    </Chip>
                                </div>
                                
                                <Divider className="my-2" />
                                
                                <div className="flex justify-between items-center my-3">
                                    <p className="text-xs text-default-500 flex items-center gap-1">
                                        过期时间:
                                    </p>
                                    <Chip
                                        size="sm"
                                        variant="dot"
                                        color={isExpired(share.expiredAt) ? "danger" : "success"}
                                    >
                                        {formatDate(share.expiredAt)}
                                    </Chip>
                                </div>
                                
                                <div className="flex justify-end items-center gap-2 mt-4">
                                    <Tooltip content="复制链接">
                                        <Button
                                            isIconOnly
                                            size="sm"
                                            variant="light"
                                            onPress={() => copyShareLink(share.token)}
                                        >
                                            <IoCopyOutline size={18} />
                                        </Button>
                                    </Tooltip>
                                    <Tooltip content="打开链接">
                                        <Button
                                            isIconOnly
                                            size="sm"
                                            variant="light"
                                            onPress={() => openShareLink(share.token)}
                                        >
                                            <MdOutlineOpenInNew size={18} />
                                        </Button>
                                    </Tooltip>
                                    <Tooltip content="取消分享" color="danger">
                                        <Button
                                            isIconOnly
                                            size="sm"
                                            variant="light"
                                            color="danger"
                                            onPress={() => {
                                                setSelectedShareId(share.id);
                                                setShowDeleteConfirm(true);
                                            }}
                                        >
                                            <HiOutlineTrash size={18} />
                                        </Button>
                                    </Tooltip>
                                </div>
                                
                                {/* 确认删除对话框 */}
                                {showDeleteConfirm && selectedShareId === share.id && (
                                    <div className="mt-3 p-3 border border-danger-200 rounded-md bg-danger-50 dark:bg-danger-900/20">
                                        <p className="text-sm text-danger mb-2">确定要取消该分享吗？</p>
                                        <div className="flex justify-end gap-2">
                                            <Button size="sm" variant="flat" onPress={() => {
                                                setShowDeleteConfirm(false);
                                                setSelectedShareId(null);
                                            }}>
                                                取消
                                            </Button>
                                            <Button size="sm" color="danger" onPress={() => handleCancelShare(share.id)}>
                                                确认取消
                                            </Button>
                                        </div>
                                    </div>
                                )}
                            </div>
                        ))}
                    </div>

                    {/* 分页控件 */}
                    {total > pageSize && (
                        <div className="flex justify-center mt-8">
                            <Button.Group>
                                <Button
                                    disabled={page === 1}
                                    onPress={() => setPage(page - 1)}
                                    variant="flat"
                                >
                                    上一页
                                </Button>
                                <Button disabled variant="flat">
                                    {page} / {Math.ceil(total / pageSize)}
                                </Button>
                                <Button
                                    disabled={page >= Math.ceil(total / pageSize)}
                                    onPress={() => setPage(page + 1)}
                                    variant="flat"
                                >
                                    下一页
                                </Button>
                            </Button.Group>
                        </div>
                    )}
                </>
            )}
        </div>
    );
} 